#include "server.h"

extern MYSQL* mySql;

//创建文件夹
int MkDir(char* path, int userId) {
    //先把要创建的目录从路径中分离出来
    char pathName[1024] = {0};
    char fileName[1024] = {0};
    int length = strlen(path) - 1;
    if(length < 0) {
        return -1;
    }
    if(path[length] == '/') {
        path[length] = 0;
        length--;
    }
    if(length < 0) {
        return -1;
    }
    int i;
    for(i = length; i >= -1; i--) {
        if(i < 0 || path[i] == '/') {
            break;
        }
    }
    strcpy(fileName, path + i + 1);
    if(i >= 0) {
        memcpy(pathName, path, i);
    }
    //分析路径，获得目录id
    printf("pathNamelen = %ld\n", strlen(pathName));
    int fileId;
    int ret = PathnameAnalyse(pathName, userId, &fileId);
    //如果创建目录的路径正确且最后一个分片为目录，则检查是否有同名的文件或目录
    if(ret == DIR_NAME) {
        int exit = 0;
        char querySentence[2048] = {0};
        sprintf(querySentence, "select id from filesystem where owner_id = %d and parent_id = %d and fileName = '%s'", 
                userId, fileId, fileName);
        ret = mysql_query(mySql, querySentence);
        if(ret != 0) {
            printf("query error: %s\n", mysql_error(mySql));
            return -1;
        }
        MYSQL_RES* result = mysql_store_result(mySql);
        if(result == NULL) {
            printf("query error: %s\n", mysql_error(mySql));
            return -1;
        }
        MYSQL_ROW row = mysql_fetch_row(result);
        if(row == NULL) {
            exit = 0;
        } else {
            exit = 1;
        }
        mysql_free_result(result);
        //如果存在则返回错误，不存在则创建目录并加入数据库
        if(exit == 1) {
            return -1;
        } else {
            memset(querySentence, 0, sizeof(querySentence));
            sprintf(querySentence, 
                    "insert into filesystem (parent_id, filename, owner_id, md5, filesize, type) values (%d, '%s', %d, '0', 0, 0)", 
                    fileId, fileName, userId);
            ret = mysql_query(mySql, querySentence);
            if(ret != 0) {
                printf("query error: %s\n", mysql_error(mySql));
                return -1;
            }
            return 0;
        }
    } else {
        return -1;
    }
}
